package com.boe.csb.core.service.user;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.boe.csb.core.common.CsbConstants;
import com.boe.csb.core.common.exception.CSBErrorCode;
import com.boe.csb.core.common.exception.CSBException;
import com.boe.csb.core.common.status.AdminUserRole;
import com.boe.csb.core.common.status.CertificationStatus;
import com.boe.csb.core.common.status.CertificationType;
import com.boe.csb.core.common.status.UserPicType;
import com.boe.csb.core.common.utils.CsbApiCaller;
import com.boe.csb.core.common.utils.FtpUtil;
import com.boe.csb.core.common.utils.MD5Utils;
import com.boe.csb.core.common.utils.MailTemplate;
import com.boe.csb.core.common.utils.MobileMsgSender;
import com.boe.csb.core.common.utils.MyRandomUtils;
import com.boe.csb.core.common.utils.PropertyUtils;
import com.boe.csb.core.common.utils.SendEmailUtil;
import com.boe.csb.core.common.utils.VerifyCodeUtils;
import com.boe.csb.core.dao.BoeUserActiveMapper;
import com.boe.csb.core.dao.BoeUserCriteria;
import com.boe.csb.core.dao.BoeUserMapper;
import com.boe.csb.core.dao.BoeUserMobilemsgMapper;
import com.boe.csb.core.dao.BoeUserSearchCriteria;
import com.boe.csb.core.dao.BoeUserSearchMapper;
import com.boe.csb.core.dao.UserOperateLogMapper;
import com.boe.csb.core.entity.ResultInfo;
import com.boe.csb.core.entity.UserInfo;
import com.boe.csb.core.entity.dto.BoeUserDTO;
import com.boe.csb.core.entity.po.BoeUser;
import com.boe.csb.core.entity.po.BoeUserActive;
import com.boe.csb.core.entity.po.BoeUserMobilemsg;
import com.boe.csb.core.entity.po.BoeUserSearch;
import com.boe.csb.core.entity.po.UserOperateLog;
import com.boe.csb.core.service.SendMailService;
import com.boe.csb.core.service.csb.CsbUserService;

/**
 * @author tianxiang.luo
 * @date 2016 - 11 - 23 上午9:42
 */
@Service(value = "boeUserService")
public class BoeUserService {

    private static String adminAccount;
    private static String adminPassword;

    static {
        adminAccount = PropertyUtils.getProperty("admin.account");
        adminPassword = PropertyUtils.getProperty("admin.password");
    }

    private static final Logger logger = LoggerFactory.getLogger(BoeUserService.class);

    private static String CHARSET = "utf-8";

    /** 设置在激活token中的分隔符*/
    private static final String TOKEN_SP = (char) 29 + "";//隐藏字符

    private static final int DB_MOBILE_REG_TYPE = 1;//数据库中标识短信信息是注册短信

    private final List<String> approvedList = Arrays.asList(CertificationStatus.ALLOW.getStatus(),CertificationStatus.REJECT.getStatus());

    @Autowired
    private BoeUserMapper boeUserMapper;

    @Autowired
    private CsbUserService csbUserService;

    @Autowired
    private BoeUserActiveMapper boeUserActiveMapper;

    @Autowired
    private SendMailService sendMailService;

    @Autowired
    private BoeUserMobilemsgMapper boeUserMobilemsgMapper;

    @Autowired
    private UserOperateLogMapper userOperateLogMapper;

    @Autowired
    private BoeUserSearchMapper boeUserSearchMapper;

    @Autowired
    private BoeUserFtpService boeUserFtpService;

    public BoeUser findBoeUser(String userId) {
        return boeUserMapper.selectUserByUserIdOrEmail(userId);
    }

    /**
     * 修改平台用户的权限接口
     */
    public void updateBoeUserRole(Long userId, String role) {
        BoeUser update = findBoeUser(String.valueOf(userId));
        if(update.getCantModify()!=null && update.getCantModify()){
            throw new CSBException(CSBErrorCode.NO_AUTH,"");
        }
        update.setRole(role);
        boeUserMapper.updateByPrimaryKey(update);
    }


    /**
     * 用户认证
     */
    @Transactional
    public void userCertification(Map<String, CommonsMultipartFile> picMap, BoeUser user, String type) throws IOException {
        boeUserMapper.updateByPrimaryKeySelective(user);
        String filePath = FtpUtil.getDatePath();
        if (CertificationType.INDIVIDUAL.getType().equals(type)) {
            //个人认证
            CommonsMultipartFile idCardPic = picMap.get(type);
            //用户修改时没有上传新的图片
            if (idCardPic != null) {
                String[] idCardStr = idCardPic.getOriginalFilename().split("\\.");
                if (idCardStr.length >= 2) {
                    String idCard = MyRandomUtils.randomUUID() + "." + idCardStr[idCardStr.length - 1];
                    //上传身份证
                    if (!FtpUtil.upload(filePath, idCard, idCardPic.getInputStream())) {
                        throw new CSBException(CSBErrorCode.ACTIVE_FAIL, "");
                    }
                    boeUserFtpService.updateUserFtp(filePath, idCard, user.getId(), UserPicType.idCard.name(), null);
                }
            }
        } else if (CertificationType.ENTERPRISE.getType().equals(type)) {
            //企业认证
            CommonsMultipartFile businessLicensePic = picMap.get(type);
            if (businessLicensePic != null) {
                String[] businessStr = businessLicensePic.getOriginalFilename().split("\\.");
                if (businessStr.length >= 2) {
                    String businessLicense = MyRandomUtils.randomUUID() + "." + businessStr[businessStr.length - 1];
                    //上传营业执照
                    if (!FtpUtil.upload(filePath, businessLicense, businessLicensePic.getInputStream())) {
                        throw new CSBException(CSBErrorCode.ACTIVE_FAIL, "");
                    }
                    boeUserFtpService.updateUserFtp(filePath, businessLicense, user.getId(), UserPicType.businessLicense.name(), null);
                }
            }
        }
    }

    /**
     * @param type 认证/
     */
    public String uploadImg(Long userId, CommonsMultipartFile pic, String type) throws IOException {
        String filePath = FtpUtil.getDatePath();
        if (pic != null) {
            String[] imgArr = pic.getOriginalFilename().split("\\.");
            if (imgArr.length >= 2) {
                String imagName = MyRandomUtils.randomUUID() + "." + imgArr[imgArr.length - 1];
                if (!FtpUtil.upload(filePath, imagName, pic.getInputStream())) {
                    throw new CSBException(CSBErrorCode.ACTIVE_FAIL, "");
                }
                if ("certification".equals(type)) {
                    boeUserFtpService.updateUserFtp(filePath, imagName, userId, UserPicType.businessLicense.name(), null);
                }
                if ("publishService".equals(type)) {
                    boeUserFtpService.insertUserFtp(userId, filePath, imagName, UserPicType.servicePic.name(), null);
                }
            }
        }
        return null;
    }



    public ResultInfo<UserInfo> userLogin(String userName, String pwd) {
        BoeUser boeUser = boeUserMapper.getUserByName(userName);
        CSBErrorCode errorCode = CSBErrorCode.SUCCESS;

        ResultInfo<UserInfo> resultInfo = new ResultInfo<UserInfo>();

        String pwdMD5 = MD5Utils.getMD5String(pwd);

        if (boeUser == null) {
            errorCode = CSBErrorCode.USER_NOT_EXIT;
        } else if (!boeUser.getPassword().equals(pwdMD5)) {
            errorCode = CSBErrorCode.PWD_ERR;
        } else if (boeUser.getActiveStatus() <= 0) {
            errorCode = CSBErrorCode.USER_NOT_ACTIVE;
        } else {
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(boeUser.getId());
            userInfo.setUserName(boeUser.getEmail());
            userInfo.setActive(boeUser.getActiveStatus());
            userInfo.setRole(boeUser.getRole());
            userInfo.setIsAdmin(boeUser.getIsAdmin());
            resultInfo.setResult(userInfo);
        }

        resultInfo.setErrorCode(errorCode);

        return resultInfo;
    }
    
    public ResultInfo<UserInfo> userLogin(String userName) {
        BoeUser boeUser = boeUserMapper.getUserByName(userName);
        CSBErrorCode errorCode = CSBErrorCode.SUCCESS;

        ResultInfo<UserInfo> resultInfo = new ResultInfo<UserInfo>();


        if (boeUser == null) {
            errorCode = CSBErrorCode.USER_NOT_EXIT;
        } else if (boeUser.getActiveStatus() <= 0) {
            errorCode = CSBErrorCode.USER_NOT_ACTIVE;
        } else {
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(boeUser.getId());
            userInfo.setUserName(boeUser.getEmail());
            userInfo.setActive(boeUser.getActiveStatus());
            userInfo.setRole(boeUser.getRole());
            userInfo.setIsAdmin(boeUser.getIsAdmin());
            resultInfo.setResult(userInfo);
        }

        resultInfo.setErrorCode(errorCode);

        return resultInfo;
    }
    
    public ResultInfo<UserInfo> userLogin(Long userId) {
        BoeUser boeUser = boeUserMapper.selectUserByUserIdOrEmail(userId.toString());
        CSBErrorCode errorCode = CSBErrorCode.SUCCESS;

        ResultInfo<UserInfo> resultInfo = new ResultInfo<UserInfo>();


        if (boeUser == null) {
            errorCode = CSBErrorCode.USER_NOT_EXIT;
        } else if (boeUser.getActiveStatus() <= 0) {
            errorCode = CSBErrorCode.USER_NOT_ACTIVE;
        } else {
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(boeUser.getId());
            userInfo.setUserName(boeUser.getEmail());
            userInfo.setActive(boeUser.getActiveStatus());
            userInfo.setRole(boeUser.getRole());
            userInfo.setIsAdmin(boeUser.getIsAdmin());
            resultInfo.setResult(userInfo);
        }

        resultInfo.setErrorCode(errorCode);

        return resultInfo;
    }

    @Transactional
    public ResultInfo<UserInfo> userRegist(String userName, String phone, String pwd , HttpSession httpSession) {

        ResultInfo<UserInfo> resutInfo = new ResultInfo<UserInfo>();

        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(pwd)) {
            throw new CSBException(CSBErrorCode.REIGST_PARAM_EMPTY, "");
        }

        String pwdMD5 = MD5Utils.getMD5String(pwd);
        CSBErrorCode errCode = CSBErrorCode.SUCCESS;
        int rst = boeUserMapper.registNewUser(userName, phone, pwdMD5, Calendar.getInstance().getTime());

        UserInfo userInfo = null;
        BoeUser boeUser = boeUserMapper.getUserByNameOrPhone(userName, phone);
        if (rst == 0) {
            if (boeUser != null) {
                if(boeUser.getEmail().equals(userName)){
                    throw new CSBException(CSBErrorCode.USER_ALREADY_EXISTS, "");
                }else{
                    throw new CSBException(CSBErrorCode.MOBILE_ALREADY_USED, "");
                }
            } else {
                logger.error("it may be never happen.");
                throw new CSBException(CSBErrorCode.UNKNOWN_ERROR, "");
            }
        } else {
            userInfo = new UserInfo();
            userInfo.setActive(boeUser.getActiveStatus());
            userInfo.setUserId(boeUser.getId());
            userInfo.setUserName(boeUser.getEmail());
            userInfo.setRole(boeUser.getRole());
            userInfo.setIsAdmin(boeUser.getIsAdmin());
            resutInfo.setResult(userInfo);
        }
        if(CSBErrorCode.SUCCESS == errCode){
//        	if(userName.endsWith("@boe.com.cn")){
//        		int activeRst = boeUserMapper.activeUser(boeUser.getId());
//                if (activeRst == 0) {
//                	errCode = CSBErrorCode.ACTIVE_FAIL;
//                }
//                httpSession.setAttribute("login", true);
//                httpSession.setAttribute("user_info", resutInfo.getResult());
//                errCode = CSBErrorCode.SUCCESS;
//        	}else{
        		errCode = sendActivateMail(userName);
//        	}
            
        }

        resutInfo.setErrorCode(errCode);

        return resutInfo;
    }

    /**
     *
     */
    public List<BoeUserDTO> listCertification(int pageNum, int limit, String type,String status) {
        BoeUserCriteria criteria = new BoeUserCriteria();
        BoeUserCriteria.Criteria subCriteria = criteria.createCriteria();
        subCriteria.andIsAdminEqualTo(Boolean.FALSE).andCertificationTypeIsNotNull();
        if(CertificationStatus.APPLYING.getStatus().equals(status)){
            subCriteria.andAuditStatusEqualTo(status);
        }else {
            subCriteria.andAuditStatusIn(approvedList);
        }
        if(type!=null){
            subCriteria.andCertificationTypeEqualTo(type);
        }
        List<BoeUser> boeUserList = boeUserMapper.selectByExampleWithBLOBsWithRowbounds(criteria, new RowBounds((pageNum - 1) * limit, limit));
        List<BoeUserDTO> dtos = new ArrayList<>();
        for (BoeUser boeUser : boeUserList) {
            BoeUserDTO dto = new BoeUserDTO();
            BeanUtils.copyProperties(boeUser, dto);
                switch (boeUser.getCertificationType()) {
                case "individual_certification":
                    dto.setIdCardPic("/api/user/getImg?userId=" + boeUser.getId() + "&type=" + UserPicType.idCard.name());
                    break;
                case "enterprise_certification":
                    dto.setBusinessLicensePic("/api/user/getImg?userId=" + boeUser.getId() + "&type=" + UserPicType.businessLicense.name());
                    break;
            }
            dtos.add(dto);
        }
        return dtos;
    }

    /**
     * v2认证
     */
    public Long countCertificationList(String type,String status) {
        BoeUserCriteria criteria = new BoeUserCriteria();
        BoeUserCriteria.Criteria subCriteria = criteria.createCriteria();
        subCriteria.andIsAdminEqualTo(Boolean.FALSE).andCertificationTypeIsNotNull();
        if(CertificationStatus.APPLYING.getStatus().equals(status)){
            subCriteria.andAuditStatusEqualTo(status);
        }else {
            subCriteria.andAuditStatusIn(approvedList);
        }
        if(type!=null){
            subCriteria.andCertificationTypeEqualTo(type);
        }
        return boeUserMapper.countByExample(criteria);
    }

    /**
     * 邮件内容
     */
    public CSBErrorCode sendActivateMail(String email) {

        Long userId = boeUserMapper.getUserId(email);
        if (userId == null || userId <= 0) {
            throw new CSBException(CSBErrorCode.USER_NOT_EXIT, "");
        }

        String tokenStr = System.currentTimeMillis() + TOKEN_SP + email + TOKEN_SP + userId;
        String decodeToken = "";
        try {
            decodeToken = URLEncoder.encode(tokenStr, CHARSET);
        } catch (UnsupportedEncodingException e) {
            logger.error("error:", e);
            throw new CSBException(CSBErrorCode.SEND_MAIL_ERR, "");
        }

        decodeToken = CsbConstants.ACTIVE_PREURL + "?token=" + decodeToken;
        String context = MailTemplate.generateActiveMail(decodeToken);
        //发送激活邮件
        sendMailService.asyncSendMail(email, CsbConstants.ACTIVE_MAIL_SUBJECT, context);

        //发送成功插入一条邮件
        BoeUserActive active = new BoeUserActive();
        active.setUserid(userId);
        active.setCreatetime(Calendar.getInstance().getTime());
        active.setActivecode(tokenStr);
        boeUserActiveMapper.insert(active);

        return CSBErrorCode.SUCCESS;
    }

    public CSBErrorCode activeUser(String decodeToken,String userId1) {
        long userId = NumberUtils.toLong(userId1, 0);
        if (userId == 0) {
            logger.error("invalid userId, tokenInfo:{}.", decodeToken);
            return CSBErrorCode.ACTIVE_INFO_ERR;
        }

        int activeStatus = boeUserMapper.getUserActiveStatus(userId);
        if (activeStatus > 0) {//已经激活
            return CSBErrorCode.USER_ALREADY_ACTIVE;
        }

        BoeUserActive boeUserActive = boeUserActiveMapper.selectByPrimaryKey(userId);
        if (boeUserActive == null) {
            return CSBErrorCode.ACTIVE_INFO_ERR;
        }

        //FIXME 是否需要校验过期时间
        if (boeUserActive.getActivecode().equals(decodeToken)) {
            int activeRst = boeUserMapper.activeUser(userId);
            if (activeRst == 0) {
                return CSBErrorCode.ACTIVE_FAIL;
            }
            return CSBErrorCode.SUCCESS;
        } else {
            return CSBErrorCode.ACTIVE_INFO_ERR;
        }
    }


    /**
     * 审核用户
     */
    public void updateCertificationStatus(List<Long> idList, String status, String adminId, String comment) {
        //更新状态
        BoeUser boeUser = new BoeUser();
        boeUser.setAuditStatus(status);
        boeUser.setIsAdmin(false);
        boeUser.setComment(comment == null ? "" : comment);
        BoeUserCriteria boeUserCriteria = new BoeUserCriteria();
        BoeUserCriteria.Criteria subCriteria = boeUserCriteria.createCriteria();
        subCriteria.andIdIn(idList);
        //通过审批的用户不能改成拒绝
        if(CertificationStatus.REJECT.getStatus().equals(status)){
            subCriteria.andAuditStatusNotEqualTo(CertificationStatus.ALLOW.getStatus());
        }
        boeUserMapper.updateByExampleSelective(boeUser, boeUserCriteria);
        List<BoeUser> boeUserList = boeUserMapper.selectByExample(boeUserCriteria);
        for (BoeUser tmp : boeUserList) {
            if (CertificationStatus.ALLOW.getStatus().equals(status)) {
                csbUserService.createCSBUser(adminId, String.valueOf(tmp.getId()), tmp.getPassword(), tmp.getEmail(), Boolean.FALSE);

                String context = MailTemplate.generateCertificationMail(CertificationStatus.ALLOW, null);
                sendMailService.asyncSendMail(tmp.getEmail(), CsbConstants.CERTIFICATION_MAIL_SUBJECT, context);
            } else {
                String context = MailTemplate.generateCertificationMail(CertificationStatus.REJECT, comment);
                sendMailService.asyncSendMail(tmp.getEmail(), CsbConstants.CERTIFICATION_MAIL_SUBJECT, context);
                //修改审核状态
                BoeUser rejUser = findBoeUser(String.valueOf(tmp.getId()));
                rejUser.setComment(comment);
                rejUser.setAuditStatus(CertificationStatus.REJECT.getStatus());
                boeUserMapper.updateByPrimaryKey(rejUser);
            }
        }
        //纪录日志
        String log = findBoeUser(String.valueOf(idList.get(0))).getEmail();
        String userName = findBoeUser(String.valueOf(Long.valueOf(adminId))).getEmail();
        String remark = String.format("管理员%s审核了用户:%s", userName, log);
        userOperateLogMapper.insert(new UserOperateLog(Long.valueOf(adminId), userName, log, AdminUserRole.USER_REGISTER.getRole(), remark, new Date()));

    }

    /**
     * 重置用户密码
     */
    public void resetPassword(Long userId, String adminPassword) {
        String password = MD5Utils.getMD5String(adminPassword);
        BoeUser updateUser = new BoeUser();
        updateUser.setId(userId);
        updateUser.setPassword(password);
        boeUserMapper.updateByPrimaryKeySelective(updateUser);
    }

    /**
     * 忘记密码, 系统重置一个随机密码, 然后发送到管理员邮箱
     */
    public void forgetPassword(String email) {
        BoeUser boeUser = boeUserMapper.selectUserByUserIdOrEmail(email);
        if (boeUser != null && email.equals(boeUser.getEmail())) {
            String newPwd = RandomStringUtils.randomAlphanumeric(8);
            resetPassword(boeUser.getId(), newPwd);

            String context = MailTemplate.generateForgetPasswordMail(newPwd);
            if (!SendEmailUtil.sendMail(email, CsbConstants.FORGET_PASSWORD_MAIL_SUBJECT, context)) {
                throw new CSBException(CSBErrorCode.SEND_MAIL_ERR, "忘记密码, 发送新密码邮件失败, " + email);
            }
        } else {
            throw new CSBException(CSBErrorCode.USER_MAIL_ERR, "忘记密码, 未找到指定邮箱, " + email);
        }
    }

    /**
     * 查询用户
     */
    public List<BoeUser> queryUser(String status, Integer pageNum, Integer limit) {
        BoeUserCriteria criteria = new BoeUserCriteria();
        criteria.createCriteria().andAuditStatusEqualTo(status);
        List<BoeUser> boeUserList = boeUserMapper.selectByExampleWithBLOBsWithRowbounds(criteria, new RowBounds((pageNum - 1) * limit, limit));
        for (BoeUser boeUser : boeUserList) {
            boeUser.setPassword(null);
        }
        return boeUserList;
    }

    public Long countUser(String status) {
        BoeUserCriteria criteria = new BoeUserCriteria();
        criteria.createCriteria().andAuditStatusEqualTo(status);
        return boeUserMapper.countByExample(criteria);
    }

    /**
     * 查询用户
     *
     * @param flag 是否取出敏感信息
     */
    public BoeUser queryBoeUser(Long userId, boolean flag) {

        BoeUser boeUser = boeUserMapper.selectByPrimaryKey(userId);
        if (flag && boeUser!=null) {
            boeUser.setPassword(null);
            boeUser.setSk(null);
            boeUser.setAk(null);
            boeUser.setRole(null);
            boeUser.setApiGroupId(null);
            boeUser.setIdCardName(null);
            boeUser.setIdCardNo(null);
            boeUser.setPhone(null);
            boeUser.setInstitutionCode(null);
            boeUser.setLegalRepresentName(null);
        }
        return boeUser;
    }


    public CSBErrorCode createAdmin(String adminId, BoeUser user) {

        //判断用户是否已经存在
        BoeUser getExists = boeUserMapper.getUserByName(user.getEmail());
        if (getExists != null) {
            return CSBErrorCode.USER_ALREADY_EXISTS;
        }

        user.setIsAdmin(true);
        boeUserMapper.insert(user);
        Long userId = user.getId();
        boolean isAdmin = true;
        csbUserService.createCSBUser(adminId, String.valueOf(userId), user.getPassword(), user.getEmail(), isAdmin);
        return CSBErrorCode.SUCCESS;
    }

    public boolean checkISAdmin(String userName) {
        BoeUser boeUser = boeUserMapper.getUserByName(userName);
        if (boeUser == null || boeUser.getIsAdmin() == null || !boeUser.getIsAdmin()) {
            return false;
        }

        return true;
    }

    /**
     * 查询
     */
    public List<BoeUser> queryBoeUserList(boolean isAdmin, Integer pageNum, Integer limit) {
        BoeUserCriteria criteria = new BoeUserCriteria();
        criteria.createCriteria().andIsAdminEqualTo(isAdmin);
        List<BoeUser> boeUserList = boeUserMapper.selectByExampleWithBLOBsWithRowbounds(criteria, new RowBounds((pageNum - 1) * limit, limit));
        for (BoeUser boeUser : boeUserList) {
            boeUser.setPassword(null);
        }
        return boeUserList;
    }


    /**
     * 发送注册短信验证码
     *
     * @param
     * @return
     */
    public CSBErrorCode sendMobileRegCode(String userName, String revNum) {

        BoeUserMobilemsg lastSend = boeUserMobilemsgMapper.getLastMobileMsgByPhone(revNum, DB_MOBILE_REG_TYPE);
        if (lastSend != null && (lastSend.getSendtime().getTime() + CsbConstants.MOBILE_MSG_SEND_GAP) > System.currentTimeMillis()) {//判断发送的频率
            return CSBErrorCode.MOBILE_VERIFY_TOO_OFTEN;
        }

        //判断手机号是不占用
        BoeUser boeUser = boeUserMapper.getUserByPhone(revNum);
        if (boeUser != null) {
            return CSBErrorCode.MOBILE_ALREADY_USED;
        }

        String verifyCode = VerifyCodeUtils.generateNumVerifyCode();
        //发送短信
        boolean sendRst = MobileMsgSender.sendRegVerifyCode(verifyCode, revNum);
        if (!sendRst) {
            return CSBErrorCode.MOBILE_SEND_ERR;
        }

        BoeUserMobilemsg mobileMsg = new BoeUserMobilemsg();
        mobileMsg.setCode(verifyCode);
        mobileMsg.setUsername(userName);
        mobileMsg.setRevnum(revNum);
        mobileMsg.setType((byte) DB_MOBILE_REG_TYPE);
        mobileMsg.setSendtime(Calendar.getInstance().getTime());
        int rst = boeUserMobilemsgMapper.insert(mobileMsg);
        if (rst == 0) {
            return CSBErrorCode.SYS_EXP;
        }

        return CSBErrorCode.SUCCESS;
    }

    /**
     * 校验短信验证码
     *
     * @param code
     * @return
     */
    public CSBErrorCode verifyMobileCode(String userName, String revNum, String code) {

        BoeUserMobilemsg mobileMsg = boeUserMobilemsgMapper.getLastMobileMsgByUser(userName, DB_MOBILE_REG_TYPE);
        if (mobileMsg == null) {
            return CSBErrorCode.MOBILE_VERIFY_CODE_NOT_EXITS;
        }

        if (!mobileMsg.getRevnum().equalsIgnoreCase(revNum.trim())) {//判断发送的手机号和提交注册的手机号是否相同
            return CSBErrorCode.MOBILE_NUM_NOT_MATCH;
        }

        long currTime = System.currentTimeMillis();
        long sendTime = mobileMsg.getSendtime().getTime();
        if (sendTime + CsbConstants.MOBILE_MSG_EXPIRED_TIME < currTime) {
            return CSBErrorCode.MOBILE_VERIFY_CODE_EXPIRED;
        }

        if (!code.equalsIgnoreCase(mobileMsg.getCode())) {
            return CSBErrorCode.MOBILE_VERIFY_CODE_ERR;
        }

        return CSBErrorCode.SUCCESS;
    }

    /**
     * 查询用户最近的搜索记录
     * @return
     */
    public List<String> queryUserLatelySearch(long userId){
    	List<String> searchList = boeUserSearchMapper.queryUserLatelySearch(userId);
    	return searchList;
    }

    /**
     * 添加用户最近的搜索记录
     */
    public void addLatelySearch(long userId, String searchName){
    	//获取当前用户的搜索记录数
    	BoeUserSearchCriteria criteria = new BoeUserSearchCriteria();
    	criteria.createCriteria().andUseridEqualTo(userId);
    	int count = (int) boeUserSearchMapper.countByExample(criteria);
    	if(count >= 6){//删除最旧的搜索记录
    		boeUserSearchMapper.deleteUserOldRow(userId);
    	}

    	criteria.clear();
    	criteria.createCriteria().andUseridEqualTo(userId).andAppnameEqualTo(searchName);
    	BoeUserSearch userSearch = new BoeUserSearch();
    	userSearch.setUserid(userId);
    	userSearch.setAppname(searchName);
    	userSearch.setModifytime(Calendar.getInstance().getTime());

    	int appNameCount = (int) boeUserSearchMapper.countByExample(criteria);
    	if(appNameCount != 0){//update
    		boeUserSearchMapper.updateByExampleSelective(userSearch, criteria);
    	}else{//insert
    		boeUserSearchMapper.insert(userSearch);
    	}
    }

    public void insertSuperAdmin(){
        BoeUserCriteria criteria = new BoeUserCriteria();
        criteria.createCriteria().andEmailEqualTo(adminAccount);
        if(!CollectionUtils.isEmpty(boeUserMapper.selectByExample(criteria))){
            throw new CSBException(CSBErrorCode.BASIC_ERROR,"");
        }
        BoeUser boeUser = new BoeUser();
        boeUser.setPassword(MD5Utils.getMD5String(adminPassword));
        boeUser.setGmtCreate(new Date());
        boeUser.setAuditStatus(CertificationStatus.ALLOW.getStatus());
        boeUser.setActiveStatus((byte)1);
        boeUser.setIsAdmin(true);
        boeUser.setCantModify(true);
        boeUser.setEmail(adminAccount);
        StringBuilder sb = new StringBuilder();
        for(String role:AdminUserRole.allRoles){
            sb.append(role).append(",");
        }
        String roles = sb.toString().substring(0,sb.length()-1);
        boeUser.setRole(roles);
        boeUserMapper.insert(boeUser);
        Long id = boeUser.getId();
        csbUserService.createCSBUser(CsbApiCaller.CSB_ADMIN_ID,String.valueOf(id),adminPassword,adminAccount,true);
    }

}
